// @Author 911ja 2022/9/28/028 14:44:00
package v2

import (
	"github.com/gin-gonic/gin"
	"github.com/wejectchen/ginblog/model"
	"github.com/wejectchen/ginblog/utils/errmsg"
	"net/http"
	"strconv"
)

// @Title       ：AddUser
// @Description ：
// @Param       ：c
// @Time        ：2022-09-28 16:12:46
// @Author      ：user
func AddUser(c *gin.Context) {
	data := model.User{}
	_ = c.ShouldBindJSON(&data)

	code := model.CheckUser(data.Username)
	if code == errmsg.SUCCESS {
		model.CreateUser(&data)
	}

	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
		"data":   data,
	})
}

// @Title       ：GetUserInfo
// @Description ：
// @Param       ：c
// @Time        ：2022-09-28 16:12:42
// @Author      ：user
func GetUserInfo(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	data, code := model.GetUser(id)
	maps := make(map[string]interface{})
	maps["id"] = data.ID
	maps["username"] = data.Username
	maps["role"] = data.Role
	total := 1
	if code == errmsg.SUCCESS {
		c.JSON(http.StatusOK, gin.H{
			"status": code,
			"msg":    errmsg.GetErrMsg(code),
			"data":   maps,
			"total":  total,
		})
	}

}

// @Title       ：GetUsers
// @Description ：
// @Param       ：c
// @Time        ：2022-09-28 16:12:51
// @Author      ：user
func GetUsers(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	username := c.Query("username")
	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 5
	}
	if pageNum <= 0 {
		pageNum = 1
	}

	data, total := model.GetUsers(username, pageSize, pageNum)
	code := errmsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
		"data":   data,
		"total":  total,
	})
}
